<script setup>
	import {
		ref,
		computed
	} from 'vue'
	import dayjs from 'dayjs'
	import {
		store
	} from '@/uni_modules/uni-id-pages/common/store.js'
	import AMapWX from '../../common/amap-wx.js'

	const info = computed(() => store.userInfo)
	const formModal = ref({
		title: '',
		image: [],
		address: '',
		isShowIndexBanner: true,
		isPublicity: true,
		userId: info.value._id,
		nickname: info.value.nickname,
		avatar: info.value.avatar_file
	})

	const rules = ref({
		title: {
			type: 'string',
			required: true,
			message: '请填写标题',
			trigger: ['blur', 'change']
		},
		address: {
			type: 'string',
			required: true,
			message: '请上传地址',
			trigger: ['blur', 'change']
		},
	})

	const uploadImg = async () => {
		const res = await uni.chooseImage({
			count: 9
		})
		if (res.errMsg !== 'chooseImage:ok') return uni.$u.toast("上传失败")

		res.tempFilePaths.forEach(async imgItem => {
			const result = await uniCloud.uploadFile({
				filePath: imgItem,
				cloudPath: `${randomFileName()}.png`,
				cloudPathAsRealPath: true
			})
			formModal.value.image.push(result.fileID)
		})
	}
	const randomFileName = () => {
		var fileName = "";
		var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
		for (var i = 0; i < 10; i++)
			fileName += possible.charAt(Math.floor(Math.random() * possible.length));
		return fileName;
	}

	const changeAddress = async () => {
		uni.getSetting({
			success: (res) => {
				let authSetting = res.authSetting;
				if (authSetting["scope.userLocation"]) {
					// 已授权
					getLocation();
				} else if (authSetting["scope.userLocation"] === false) {
					uni.showModal({
						title: "您未开启地理位置授权",
						content: "请在系统设置中打开位置授权，以便我们为您提供更好的服务",
						success: (res) => {
							if (res.confirm) {
								uni.openSetting();
							}
						},
					});
				} else {
					uni.authorize({
						scope: "scope.userLocation",
						success: () => {
							getLocation();
						},
						fail: () => {
							uni.showModal({
								title: "您未开启地理位置授权",
								content: "请在系统设置中打开位置授权，以便我们为您提供更好的服务",
								success: (res) => {
									if (res.confirm) {
										uni.openSetting();
									}
								},
							});
						},
					});
				}
			},
		});
	}
	const getLocation = () => {
		try {
			uni.showLoading({title:'获取位置中'})
			const amapPlugin = new AMapWX.AMapWX({
				key: '693be364637411f275885c7ee25ca7db'
			});
			amapPlugin.getRegeo({
				success(res){
					console.log("12321321",res)
					formModal.value.address = res[0].name 
				},
			})
			uni.hideLoading()
		} catch {
			console.log("获取失败")
		}
	}

	const addFrom = ref()
	const db = uniCloud.database();
	const submit = () => {
		addFrom.value.validate().then(async res => {
			const query = {
				...formModal.value,
				createTime: dayjs().format('YYYY-MM-DD HH:mm:ss')
			}
			try {
				uni.showLoading({
					title: "加载中..."
				})
				await db.collection('dynamic_list').add(query)
				uni.hideLoading()
				uni.navigateBack()
			} catch (err) {
				uni.$u.toast(err)
			}
		}).catch(err => {})
	}
</script>

<template>
	<view class="content">
		<u--form labelPosition="left" :model="formModal" :rules="rules" ref="addFrom">
			<u-form-item label="标题:" prop="title" borderBottom required>
				<u--input v-model="formModal.title" border="none"></u--input>
			</u-form-item>
			<u-form-item label="图片:" borderBottom>
				<view class="img_content">
					<u--image class="image" width="170rpx" height="170rpx" v-for="(item,index) in formModal.image"
						:key="index" :src="item"></u--image>
					<view class="img_list" @click="uploadImg">
						<u-icon name="plus"></u-icon>
						<text style="margin-top: 20rpx;">上传图片</text>
					</view>
				</view>
			</u-form-item>
			<u-form-item label="地址 :" prop="address" borderBottom required>
				<view @click="changeAddress">
					<u--input v-model="formModal.address" type="textarea" disabled readonly disabledColor="#ffffff"
						placeholder="请选择当前地址" border="none"></u--input>
				</view>
			</u-form-item>
			<u-form-item label="图片将其展示在首页" borderBottom labelWidth="520rpx">
				<u-switch v-model="formModal.isShowIndexBanner" size="20"></u-switch>
			</u-form-item>
			<u-form-item label="是否在公开展示" borderBottom labelWidth="520rpx">
				<u-switch v-model="formModal.isPublicity" size="20"></u-switch>
			</u-form-item>
		</u--form>
		<view class="footer">
			<u-button type="primary" @click="submit">提交</u-button>
		</view>
	</view>

</template>

<style lang="scss" scoped>
	.content {
		padding: 0 40rpx;
		padding-bottom: 200rpx;
	}

	.img_content {
		display: grid;
		grid-template-columns: repeat(3, 1fr);
		grid-row-gap: 10rpx;
	}

	.img_list {
		display: flex;
		justify-content: center;
		align-items: center;
		flex-direction: column;
		width: 170rpx;
		height: 170rpx;
		border: 1px solid #eee;
	}

	.footer {
		position: fixed;
		left: 50%;
		bottom: 0;
		transform: translateX(-50%);
		width: 90%;
		padding: 20rpx 0 40rpx;
		background: #fff;
	}
</style>